package netWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class My_TcpClient {
    private Socket socket = null;
    public My_TcpClient(String IP, int port) throws IOException {
        socket=new Socket(IP,port);
    }
    public void start() {
        System.out.println("和服务器连接成功!");
        Scanner scanner = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream()) {
            try (OutputStream outputStream = socket.getOutputStream()) {
                while (scanner.hasNext()){
                    String request= scanner.next();
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();
                    Scanner respScanner = new Scanner(inputStream);
                    String response = respScanner.next();
                    System.out.printf("req: %s, resp: %s\n", request, response);

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }

}
